package org.example.backend.demos.web.config;

import org.example.backend.demos.web.filter.jwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.AuthorizationFilter;


@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private jwtAuthenticationFilter jwtAuthentication;

    @Autowired
    private UserDetailsService authService;


    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    public AuthenticationManager authenticationManager() {
        DaoAuthenticationProvider Provider = new DaoAuthenticationProvider();
        Provider.setUserDetailsService(authService);
        Provider.setPasswordEncoder(bCryptPasswordEncoder());
        return new ProviderManager(Provider);

    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                        .requestMatchers("/api/auth/login", "/api/auth/register", "/news/api/allnews", "/projects/api/allproject","/cos/api/user/upimage","/cos/api/user/downimage").permitAll()
                        .requestMatchers("/projects/api/{id}", "/news/api/page","/projects/api/page", "/news/api/{id}", "/api/auth/check-username","/api/auth/check-phone").permitAll()
                        .anyRequest().authenticated())
                .csrf(AbstractHttpConfigurer::disable)
                .cors(Customizer.withDefaults())
                .sessionManagement(AbstractHttpConfigurer::disable);


//        http.formLogin(form->form.successHandler(new SuccessHandler()).failureHandler(new FailureHandler()));
        http.formLogin(AbstractHttpConfigurer::disable);

        http.addFilterBefore(jwtAuthentication, AuthorizationFilter.class);
        return http.build();
    }
}
